<template>
  <div class="dept-container">
    <filter-layout class="filter-container">
      <template #search>
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="searchForm.name" placeholder="请输入" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="fetchDeptList">查询</el-button>
          </el-form-item>
        </el-form>
      </template>
      <template #button>
        <el-button v-permission="['system:dept:add']" type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        <el-button type="info" :icon="Sort" plain @click="handleToggleExpandAll">展开/折叠</el-button>
      </template>
    </filter-layout>
    <lyf-table
      v-if="reRenderTable"
      :columns="columns"
      :data="tableData"
      border
      :max-height="tableHeight"
      :default-expand-all="isExpandAll"
      row-key="id"
    ></lyf-table>
    <save-dept
      v-model="saveDialogVisible"
      :data="saveDialogData"
      :parent-id="saveParentId"
      :dialog-type="saveDialogType"
      @success="fetchDeptList"
    ></save-dept>
  </div>
</template>
<script setup lang="tsx">
import { ref, nextTick, onMounted, VNode } from 'vue'
import { Search, Plus, Edit, Delete, Sort } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import LyfTable from '@/components/lyf-table/index.vue'
import FilterLayout from '@/components/page-layout/filter-layout.vue'
import SaveDept from './save-dept.vue'

import { IDept, IQueryParams } from '@/api/dept/types'
import { getDeptList, deleteDept } from '@/api/dept/index'
import { formatDate, arrayToTree } from '@/utils/utils'
import { DialogTypeEnum } from '@/api/common/types'
import { hasPermissionShowDOM } from '@/directives/permission/permission'

const searchForm = ref<IQueryParams>({
  name: ''
})

const tableHeight = ref(400)
const columns = [
  {
    label: '部门名称',
    prop: 'name'
  },
  {
    label: '排序',
    prop: 'sort',
    align: 'center',
    width: 100
  },
  {
    label: '创建时间',
    prop: 'createTime',
    align: 'center',
    slot: (h: () => VNode, { row }: { row: IDept }) => {
      return <span>{row.createTime && formatDate(new Date(row.createTime), 'yyyy-MM-dd HH:mm:ss')}</span>
    }
  },
  {
    label: '编辑时间',
    prop: 'updateTime',
    align: 'center',
    slot: (h: () => VNode, { row }: { row: IDept }) => {
      return <span>{row.updateTime && formatDate(new Date(row.updateTime), 'yyyy-MM-dd HH:mm:ss')}</span>
    }
  },
  {
    label: '操作',
    width: 220,
    align: 'center',
    fixed: 'right',
    slot: (h: () => VNode, { row }: { row: IDept }) => {
      return (
        <div>
          {hasPermissionShowDOM(
            ['system:dept:add'],
            <el-button
              type="primary"
              link
              icon={Plus}
              onClick={() => {
                handleAdd(row)
              }}
            >
              新增
            </el-button>
          )}

          {hasPermissionShowDOM(
            ['system:dept:edit'],
            <el-button
              type="primary"
              link
              icon={Edit}
              onClick={() => {
                handleEdit(row)
              }}
            >
              编辑
            </el-button>
          )}
          {hasPermissionShowDOM(
            ['system:dept:delete'],
            <el-button type="danger" link icon={Delete} onClick={() => handleDelete(row)} class="danger-btn">
              删除
            </el-button>
          )}
        </div>
      )
    }
  }
]
const tableData = ref<IDept[]>([])

/**
 * 计算表格高度
 */
const computedTableHeight = () => {
  nextTick(() => {
    const container: HTMLDivElement = document.querySelector('.dept-container') as HTMLDivElement
    const filterContainer: HTMLDivElement = document.querySelector('.filter-container') as HTMLDivElement
    tableHeight.value = container.offsetHeight - filterContainer.offsetHeight - 10 // 10 margin
  })
}

// 表格展开行
const reRenderTable = ref(true)
const isExpandAll = ref(true)
/**
 * 展开/折叠
 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value
  reRenderTable.value = false
  nextTick(() => {
    reRenderTable.value = true
  })
}

/**
 * 获取部门列表
 */
const fetchDeptList = () => {
  getDeptList(searchForm.value).then(({ data }) => {
    tableData.value = arrayToTree(data || [])
  })
}

// 新增、编辑
const saveDialogVisible = ref(false)
const saveDialogData = ref()
const saveDialogType = ref(DialogTypeEnum.ADD)
const saveParentId = ref()

/**
 * 新增
 * @param {IDept} dept
 */
const handleAdd = (dept?: IDept) => {
  if (dept) {
    saveParentId.value = dept.id
  }
  saveDialogType.value = DialogTypeEnum.ADD
  saveDialogVisible.value = true
}
/**
 * 编辑
 * @param {IDept} dept
 */
const handleEdit = (dept: IDept) => {
  saveDialogType.value = DialogTypeEnum.EDIT
  saveDialogData.value = dept
  saveDialogVisible.value = true
}

/**
 * 删除
 * @param {IDept} dept
 */
const handleDelete = (dept: IDept) => {
  ElMessageBox.confirm('是否确认删除', '警告', { type: 'warning' })
    .then(() => {
      deleteDept(dept.id).then(() => {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        fetchDeptList()
      })
    })
    .catch(() => {})
}

onMounted(() => {
  computedTableHeight()
  fetchDeptList()
})
</script>
<style scoped lang="scss">
.dept-container {
  height: 100%;

  .search-form {
    .el-form-item {
      margin-right: 10px;
    }
  }
}
</style>
